const net = require('net');
const fs = require('fs')
const server = net.createServer((socket) => {
  socket.on('data', (data) => {
    let request = data.toString();
    let [requestLine, ...headerRows] = request.split('\r\n');
    let [method, path] = requestLine.split(' ');
    let headers = headerRows.slice(0, -2).reduce((memo, row) => {
      let [key, value] = row.split(': ');
      memo[key] = value;
      return memo;
    }, {});
    console.log('method', method);
    console.log('path', path);
    console.log('headers', headers);
    var obj = {
      method,
      path,
      headers
    }
    let rows = []
    if(path==='/'){
              rows = [];
             rows.push(`HTTP/1.1 200 OK`);
             rows.push(`Context-type: text-plain`);
             rows.push(`Date: ${new Date().toGMTString()}`);
             rows.push(`Connection: keep-alive`);
             rows.push(`Transfer-Encoding:  chunked`);
             let responseBody = `${fs.readFileSync('./static/get.html','utf8')}`;
            // let responseBody = `${JSON.stringify(obj)}`;
            //  console.log(responseBody)
             rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);
    }
    
    if(path==='/get'){
         rows.push(`HTTP/1.1 200 OK`);
         rows.push(`Context-type: text-plain`);
         rows.push(`Date: ${new Date().toGMTString()}`);
         rows.push(`Connection: keep-alive`);
         rows.push(`Transfer-Encoding: chunked`);
          let responseBody = `{"name":"124"}`;
          rows.push(`\r\n${Buffer.byteLength(responseBody).toString(16)}\r\n${responseBody}\r\n0\r\n\r\n`);
    }
 
    let response = rows.join('\r\n');
    socket.write(Buffer.from(response))
    socket.end();
  });
})
server.on('error', (err) => {
  console.error(err);
});

server.listen(5555, () => {
  console.log('服务器已经启动', server.address());
});